<?php
namespace app\channel\controller;
use think\Controller;
use think\Db;

class Show extends Controller
{
    public function index(){
        echo 'channel-show';
    }

    public function login(){
        if(request()->isAjax()){
            $where['account'] = input('account');
            $where['password'] = md5(input('password'));
            $where['status'] = ['<>', -1];
            if( ! $select = Db::name('ViewChannel')->where($where)->select() ){
                $this->layJson(1, '账号或者密码错误');
            }

            $cps = [];
            $sdk = [];
            foreach ($select as $k=>$v){
                if($v['channel_id']==1000){
                    $cps = $v;
                }

                if($v['channel_id']>=5000){
                    $sdk = $v;
                }
            }

            if($cps){
                if($cps['status']!==1){
                    $this->layJson(1, '该CPS账号被禁用，请联系管理员');
                }

                session('admin.cps_account', $cps['account']);
                session('admin.cps_password', $cps['password']);
                session('admin.cps_id', $cps['cps_id']);
                session('admin.cps_name', $cps['cps_name']);
                session('admin.cps_pid', $cps['pid']);
                if($cps['login_time']){
                    session('admin.cps_login_time', date('Y-m-d H:i:s', $cps['login_time']));
                }else{
                    session('admin.cps_login_time', '公元前');
                }

                Db::name('Channel')->where('cps_id', $cps['cps_id'])->update([
                    'login_time' => time(),
                    'login_ip' => request()->ip()
                ]);
            }

            if($sdk){
                if($sdk['status']!==1){
                    $this->layJson(1, '该SDK账号被禁用，请联系管理员');
                }

                session('admin.sdk_account', $sdk['account']);
                session('admin.sdk_password', $sdk['password']);
                session('admin.sdk_id', $sdk['channel_id']);
                session('admin.sdk_name', $sdk['channel_name']);
                if($sdk['login_time']){
                    session('admin.sdk_login_time', date('Y-m-d H:i:s', $sdk['login_time']));
                }else{
                    session('admin.sdk_login_time', '公元前');
                }

                Db::name('Channel')->where('channel_id', $sdk['channel_id'])->update([
                    'login_time' => time(),
                    'login_ip' => request()->ip()
                ]);
            }

            session('admin.start_time', time());

            $this->layJson(0, '登录中....');
        }else{
            return view();
        }
    }

    protected function layJson($code=0, $msg='', $data=[], $count=0){
        $json['code'] = $code;
        $json['msg'] = $msg;
        $json['data'] = $data;
        $json['count'] = $count;
        echo json_encode($json);exit;
    }
}